<template>
  <div>
    <!-- 搜索区域：两行布局 -->
    <div class="filter-toolbar-2rows">
      <!-- 第一行：只放 日期 -->
      <div class="filter-row">
        <el-select
            v-model="filters.mealCalendarDate"
            placeholder="选择日期"
            clearable
            style="width: 140px;"
            @change="onSearch"
        >
          <el-option
              v-for="opt in dateOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
          />
        </el-select>
        <el-select
            v-model="filters.mealCalendarTime"
            placeholder="时段"
            clearable
            style="width: 120px;"
            @change="onSearch"
        >
          <el-option
              v-for="opt in timeOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
          />
        </el-select>
      </div>

      <!-- 第二行：左筛选 + 右侧按钮 -->
      <div class="filter-row second-row">
        <div class="filter-left">

          <el-select
              v-model="filters.foodType"
              placeholder="食物类型"
              clearable
              style="width: 160px;"
              @change="onSearch"
          >
            <el-option
                v-for="opt in foodTypeOptionsFull"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
            />
          </el-select>
          <el-input
              v-model="filters.foodName"
              placeholder="食物名称"
              clearable
              style="width: 180px;"
              @clear="onSearch"
              @keyup.enter="onSearch"
          />
          <el-button type="primary" @click="onSearch">
            <el-icon><Search/></el-icon>
          </el-button>
        </div>

        <div class="filter-right">
          <el-button type="success" @click="openDialog()">新增膳食日历</el-button>
          <el-button type="info" @click="openFoodManager">查看食物列表</el-button>
        </div>
      </div>
    </div>

    <!-- 列表 -->
    <el-table
        v-if="tableData.length"
        :data="tableData"
        border
        stripe
        style="width: 100%; margin-top: 16px"
    >
      <el-table-column type="index" label="序号" width="60"/>
      <el-table-column prop="mealCalendarDate" label="日期" width="120"/>
      <el-table-column prop="mealCalendarTime" label="时段" width="100"/>
      <el-table-column prop="foodType" label="食物类型"/>
      <el-table-column prop="foodName" label="食物名称"/>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button
              size="small"
              type="primary"
              @click="openDialog(row)"
          >调换
          </el-button>
          <el-button
              size="small"
              type="warning"
              @click="onDisable(row.mealCalendarId)"
          >停用
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-else class="empty">暂无启用的膳食日历</div>

    <!-- 分页 -->
    <div style="margin-top:16px; text-align:right;">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[5,10,20,50]"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
      />
    </div>
    <!-- 食物管理 Dialog -->
    <el-dialog
        title="食物管理"
        v-model="foodManagerVisible"
        width="700px"
        @close="resetFoodManager"
    >
      <!-- 搜索 条件 + 新增 -->
      <div style="margin-bottom: 16px; display: flex; align-items: center;">
        <el-select
            v-model="foodFilters.foodType"
            placeholder="食物类型"
            clearable
            style="width: 180px; margin-right: 12px"
            @change="fetchFoodList"
        >
          <el-option
              v-for="opt in foodTypeOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
          />
        </el-select>

        <el-input
            v-model="foodFilters.foodName"
            placeholder="食物名称"
            clearable
            style="width: 180px; margin-right: 12px"
            @clear="fetchFoodList"
            @keyup.enter="fetchFoodList"
        />
        <el-button type="primary" @click="fetchFoodList">
          <el-icon>
            <Search/>
          </el-icon>
          搜索
        </el-button>
        <el-button
            type="success"
            @click="openFoodForm()"
            style="margin-left: auto"
        >新增食物
        </el-button>
      </div>

      <!-- 食物列表 Table -->
      <el-table
          v-if="foodTable.data.length"
          :data="foodTable.data"
          stripe
          border
          style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60"/>
        <el-table-column prop="foodName" label="名称"/>
        <el-table-column prop="calories" label="卡路里" width="100"/>
        <el-table-column prop="foodType" label="类型" width="120"/>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button
                size="small"
                type="primary"
                @click="openFoodForm(row)"
            >编辑
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="onDeleteFood(row.foodId)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-else class="empty">暂无数据</div>


      <!-- 分页 -->
      <div style="margin-top:16px; text-align:right;">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="foodTable.total"
            v-model:current-page="foodTable.page"
            v-model:page-size="foodTable.size"
            :page-sizes="[5,10,20,50]"
            @current-change="onFoodPageChange"
            @size-change="onFoodSizeChange"
        />
      </div>

      <!-- 新增/编辑 食物 Form 子弹窗 -->
      <el-dialog
          :title="isEditingFood ? '编辑食物' : '新增食物'"
          v-model="foodFormVisible"
          width="480px"
          @close="resetFoodForm"
      >
        <el-form :model="foodForm" label-width="100px">
          <el-form-item label="类型">
            <el-select
                v-model="foodForm.foodType"
                placeholder="选择食物类型"
                clearable
            >
              <el-option
                  v-for="opt in foodTypeOptions.slice(1)"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="foodForm.foodName"/>
          </el-form-item>
          <el-form-item label="卡路里">
            <el-input-number v-model="foodForm.calories" :min="0"/>
          </el-form-item>

        </el-form>
        <template #footer>
          <el-button @click="foodFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitFoodForm">
            {{ isEditingFood ? '保存' : '创建' }}
          </el-button>
        </template>
      </el-dialog>
    </el-dialog>
    <!-- 新增/修改 Dialog -->
    <el-dialog
        :title="isEditing ? '修改膳食日历' : '新增膳食日历'"
        v-model="showDialog"
        width="480px"
        @close="resetForm"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="日期">
          <el-select
              v-model="form.mealCalendarDate"
              placeholder="选择日期"
          >
            <el-option
                v-for="opt in dateOptions.slice(1)"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="时段">
          <el-select
              v-model="form.mealCalendarTime"
              placeholder="选择时段"
          >
            <el-option
                v-for="opt in timeOptions.slice(1)"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="食物类型">
          <el-select
              v-model="form.foodType"
              placeholder="选择食物类型"
              :loading="loadingFoods"
              clearable
              @change="onTypeChange"
          >
            <el-option
                v-for="type in foodTypeOptions"
                :key="type"
                :label="type"
                :value="type"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="食物名称">
          <el-select
              v-model="form.foodId"
              placeholder="先选食物类型"
              :disabled="!form.foodType"
              :loading="loadingFoods"
              filterable
              @change="onFoodChange"
          >
            <el-option
                v-for="f in foods"
                :key="f.foodId"
                :label="f.foodName"
                :value="f.foodId"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">
          {{ isEditing ? '保存' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>

</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Search} from '@element-plus/icons-vue'
import {
  listMealCalendars,   // now accepts (filters, page, size)
  createMealCalendar,
  updateMealCalendar
} from '@/api/apiList/mealCalendar'
import {
  listFoods,
  createFood,
  updateFood,
  deleteFood,
  listFoodsChange
} from '@/api/apiList/food'

// 表格数据 & 筛选
const tableData = ref([])
const filters = reactive({
  mealCalendarDate: '',
  mealCalendarTime: '',
  foodName: '',
  foodType: ''
})
const FOOD_TYPES = [
  '蔬菜',
  '水果',
  '肉类',
  '海鲜',
  '蛋类',
  '奶制品',
  '豆制品',
  '主食',
  '饮料',
  '其他'
]

const dateOptions = [
  {label: '全部', value: ''},
  {label: '周一', value: '周一'},
  {label: '周二', value: '周二'},
  {label: '周三', value: '周三'},
  {label: '周四', value: '周四'},
  {label: '周五', value: '周五'},
  {label: '周六', value: '周六'},
  {label: '周日', value: '周日'}
]
const timeOptions = [
  {label: '全部', value: ''},
  {label: '早', value: '早'},
  {label: '午', value: '午'},
  {label: '晚', value: '晚'}
]

// 分页状态
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})
function onFoodSizeChange(size) {
  foodTable.size = size;
  foodTable.page = 1; // 重置到第一页
  fetchFoodList();
}
// 拉取列表（含分页）
async function fetchList() {
  try {
    const params = {
      ...filters,
      page: pagination.current,
      size: pagination.size
    }
    const pageData = await listMealCalendars(params)
    // 过滤只显示“启用”状态
    tableData.value = pageData.records.filter(r => r.mealCalendarStatus === '启用')
    // 总数仍用后端返回的 total
    pagination.total = pageData.total
  } catch {
    ElMessage.error('获取失败')
  }
}

function onSearch() {
  pagination.current = 1
  fetchList()
}

function handlePageChange(page) {
  pagination.current = page
  fetchList()
}

function handleSizeChange(size) {
  pagination.size = size
  pagination.current = 1
  fetchList()
}

// Dialog & 表单状态
const showDialog = ref(false)
const isEditing = ref(false)
const form = reactive({
  mealCalendarId: null,
  mealCalendarDate: '',
  mealCalendarTime: '',
  foodType: '',
  foodId: null,
  foodName: ''
})

// 食物类型 & 列表
const foods = ref([])
const loadingFoods = ref(false)

async function loadTypes() {
  loadingFoods.value = true
  try {
    const all = await listFoods()
    foodTypeOptions.value = [...new Set(all.map(f => f.foodType))]
  } finally {
    loadingFoods.value = false
  }
}

async function onTypeChange() {
  form.foodId = null
  if (!form.foodType) {
    foods.value = []
    return
  }
  loadingFoods.value = true
  try {
    foods.value = await listFoods(form.foodType)
  } finally {
    loadingFoods.value = false
  }
}

function onFoodChange(id) {
  const sel = foods.value.find(f => f.foodId === id)
  form.foodName = sel ? sel.foodName : ''
}

const foodTypeOptionsFull = ref([
  ...FOOD_TYPES.map(type => ({label: type, value: type}))
])

async function openDialog(row = null) {
  resetForm()
  isEditing.value = !!row
  await loadTypes()
  if (row) {
    Object.assign(form, {
      mealCalendarId: row.mealCalendarId,
      mealCalendarDate: row.mealCalendarDate,
      mealCalendarTime: row.mealCalendarTime,
      foodType: row.foodType,
      foodId: row.foodId,
      foodName: row.foodName
    })
    await onTypeChange()
  }
  showDialog.value = true
}

function resetForm() {
  form.mealCalendarId = null
  form.mealCalendarDate = ''
  form.mealCalendarTime = ''
  form.foodType = ''
  form.foodId = null
  form.foodName = ''
  foods.value = []
}

async function submitForm() {
  try {
    if (isEditing.value) {
      await updateMealCalendar(form)
      ElMessage.success('修改成功')
    } else {
      await createMealCalendar(form)
      ElMessage.success('新增成功')
    }
    showDialog.value = false
    fetchList()
  } catch {
    ElMessage.error((isEditing.value ? '修改' : '新增') + '失败')
  }
}

async function onDisable(id) {
  try {
    await ElMessageBox.confirm('确认停用？', '提示', {type: 'warning'})
    await updateMealCalendar({mealCalendarId: id, mealCalendarStatus: '停用'})
    ElMessage.success('已停用')
    fetchList()
  } catch {
  }
}

// —— 食物管理 新增状态 —— //
const foodManagerVisible = ref(false)

function openFoodManager() {
  foodManagerVisible.value = true
  resetFoodManager()
  fetchFoodList()
}

function resetFoodManager() {
  foodFilters.foodType = ''
  foodFilters.foodName = ''
  foodTable.page = 1
}

const foodTypeOptions = ref([{label: '全部', value: ''}].concat(
    FOOD_TYPES.map(t => ({label: t, value: t}))
))
// 搜索条件 & 分页数据
const foodFilters = reactive({
  foodType: '',
  foodName: ''
})
const foodTable = reactive({
  data: [],
  page: 1,
  size: 10,
  total: 0
})

// 拉取食物列表（前端简单分页/过滤）
async function fetchFoodList() {
  try {
    const resp = await listFoodsChange({
      foodType: foodFilters.foodType,
      foodName: foodFilters.foodName,
      page: foodTable.page,
      size: foodTable.size
    })
    foodTable.data = resp.records
    foodTable.total = resp.total
  } catch {
    ElMessage.error('获取食物列表失败')
  }
}

function onFoodPageChange(page) {
  foodTable.page = page
  fetchFoodList()
}

// 新增/编辑 Form 状态
const foodFormVisible = ref(false)
const isEditingFood = ref(false)
const foodForm = reactive({
  foodId: null,
  foodName: '',
  foodType: '',    // 下拉绑定
  calories: 0
})

function openFoodForm(row = null) {
  isEditingFood.value = !!row
  if (row) {
    Object.assign(foodForm, {
      foodId: row.foodId,
      foodName: row.foodName,
      foodType: row.foodType,
      calories: row.calories
    })
  } else {
    resetFoodForm()
  }
  foodFormVisible.value = true
}

function resetFoodForm() {
  foodForm.foodId = null
  foodForm.foodName = ''
  foodForm.foodType = ''
  foodForm.calories = 0
}

async function submitFoodForm() {
  try {
    if (isEditingFood.value) {
      await updateFood(foodForm)
      ElMessage.success('修改成功')
    } else {
      await createFood(foodForm)
      ElMessage.success('新增成功')
    }
    foodFormVisible.value = false
    fetchFoodList()
  } catch {
    ElMessage.error((isEditingFood.value ? '修改' : '新增') + '失败')
  }
}

async function onDeleteFood(id) {
  try {
    await ElMessageBox.confirm('确认删除？', '提示', {type: 'warning'})
    await deleteFood(id)
    ElMessage.success('删除成功')
    if (foodTable.data.length === 1 && foodTable.page > 1) {
      foodTable.page--
    }
    fetchFoodList()
  } catch {
  }
}

onMounted(fetchList)
</script>

<style scoped>
.empty {
  text-align: center;
  margin: 40px 0;
  color: #888;
}
.filter-toolbar-2rows {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 16px 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  margin-bottom: 16px;
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.second-row {
  justify-content: space-between;
}

.filter-left {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  align-items: center;
}

.filter-right {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}
.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-dialog .el-form {
  padding: 0 20px;
}

.el-dialog .el-form-item {
  margin-bottom: 16px;
}

.el-button {
  border-radius: 6px;
  min-width: 40px;
}
</style>
